
#code to replicate matching analysis of Walter et al. "Non-Cooperation by popular vote "

#install.packages("foreign")
#install.packages("rgenoud")
#install.packages("Matching")
#install.packages("survey")
#install.packages("ebal")
#install.packages("lattice")
#install.packages("ggplot2")
#install.packages("gridExtra")
#install.packages("rio")

rm(list=ls())
library(foreign)
library(rgenoud)
library(Matching)
library(survey)
library(ebal)
library(lattice)
library(ggplot2)
library(gridExtra)
library("rio")
install_formats()




setwd("/path/to/replication/directory/")

dat <- read.table("genmatch1.csv",header=T)

covars <- c("age1","age2","age3","age4","age5","age6","unemployed","publicsector","privatesector","entrepreneur","farmer","otherocc","ed1","ed2","ed3","ed4","female","rural","syriza","anel","pasok","river","goldendawn","abstain","other","stayeuro","leaveeuro","prscore")

X <- as.matrix(dat[,covars])


dat    <- data.frame(dat[,(names(dat) %in% covars)==F],X)
covars <- names(dat)[-which((names(dat) %in% c("grexitbelief","referendumno")))]
X     <- dat[,covars]
X     <- as.matrix(X)
colnames(X) <-gsub("age1","18-24",colnames(X))
colnames(X) <-gsub("age2","25-34",colnames(X))
colnames(X) <-gsub("age3","35-44",colnames(X))
colnames(X) <-gsub("age4","45-54",colnames(X))
colnames(X) <-gsub("age5","55-64",colnames(X))
colnames(X) <-gsub("age6","65+",colnames(X))
colnames(X) <-gsub("unemployed","Unemployed",colnames(X))
colnames(X) <-gsub("publicsector","Public Sector",colnames(X))
colnames(X) <-gsub("privatesector","Private Sector",colnames(X))
colnames(X) <-gsub("entrepreneur","Entrepreneur",colnames(X))
colnames(X) <-gsub("farmer","Farmer",colnames(X))
colnames(X) <-gsub("otherocc","Other Occup.",colnames(X))
colnames(X) <-gsub("ed1","Primary Ed.",colnames(X))
colnames(X) <-gsub("ed2","Secondary Ed.",colnames(X))
colnames(X) <-gsub("ed3","Post-Secondary Ed.",colnames(X))
colnames(X) <-gsub("ed4","College",colnames(X))
colnames(X) <-gsub("female","Female",colnames(X))
colnames(X) <-gsub("rural","Rural",colnames(X))
colnames(X) <-gsub("syriza","Syriza",colnames(X))
colnames(X) <-gsub("anel","Ind.Greeks",colnames(X))
colnames(X) <-gsub("pasok","PASOK",colnames(X))
colnames(X) <-gsub("river","River",colnames(X))
colnames(X) <-gsub("goldendawn","Golden Dawn",colnames(X))
colnames(X) <-gsub("abstain","Abstain",colnames(X))
colnames(X) <-gsub("other","Other",colnames(X))
colnames(X) <-gsub("stayeuro","Stay in Euro",colnames(X))
colnames(X) <-gsub("leaveeuro","Leave Euro",colnames(X))
colnames(X) <-gsub("prscore","Propensity Score",colnames(X))
dat <- data.frame(dat,X)
Y <- dat$referendumno
W <- dat$grexitbelief


g.weights <- GenMatch(Tr=W, X=X, BalanceMatrix=X, pop.size = 5000, estimand="ATT", M=1,print.level=0)
mout.gm <-  Match(Y,W,X,BiasAdjust=F,Weight.matrix=g.weights,estimand="ATT",M=1)
summary(mout.gm)
bout.gm <- MatchBalance(W~X,match.out = mout.gm,print.level=0)
bal.gm <- baltest.collect(matchbal.out=bout.gm,var.names=colnames(X),after=TRUE)
round(bal.gm,3)


plot.pval <- function(mb.results, covariates, title=NULL, means=TRUE, legend=TRUE,
                      legendx=0.15,legendy=2.2, textsize=0.9, parcex=0.8, at1=-0.35,
                      at2=-0.15, at3=-0.9,xlim1=-0.85){
  
  
  ## Check to make sure "covariates" is either a character vector or a matrix
  if(!(is.character(covariates)) & !(is.matrix(covariates))){
    stop("Error: The covariates must be either a character vector or a matrix with variable names")
  }
  
  
  
  balanceMat <- function(mb.results, covariates){
    
    ## Calculate the number of covariates
    ## If "covariates" is a matrix, take the number of columns; otherwise, take the number of
    ## elements in the vector
    n <- ifelse(class(covariates)=="matrix", dim(covariates)[2], length(covariates))
    
    ## Check to make sure that n is the same as the # of balance statistics
    bsCount <- length(mb.results$BeforeMatching)
    if(n != bsCount){stop("Error: the number of covariates does not match the size of the MatchBalance Results.")}
    
    ## Determine how the covariate names are provided, and then grab them
    if(class(covariates)=="matrix") rnames <- dimnames(covariates)[[2]]
    if(class(covariates)=="character") rnames <- covariates
    
    ## Construct the matrix of statistics from the MatchBalance data and attach it to the covariate names
    z <- t(sapply(1:n, function(x){
      c(rnames[x],
        round(mb.results$AfterMatching[[x]]$mean.Tr,3),
        round(mb.results$AfterMatching[[x]]$mean.Co,3),
        round(mb.results$BeforeMatching[[x]]$tt$p.value,2),
        round(mb.results$AfterMatching[[x]]$tt$p.value,2),
        round(mb.results$BeforeMatching[[x]]$tt$statistic,2),
        round(mb.results$AfterMatching[[x]]$tt$statistic,2),
        ifelse(is.null(mb.results$BeforeMatching[[x]]$ks$ks.boot.pvalue) ==
                 0,round(mb.results$BeforeMatching[[x]]$ks$ks.boot.pvalue,2),
               NA),
        
        ifelse(is.null(mb.results$AfterMatching[[x]]$ks$ks.boot.pvalue) ==
                 0, round(mb.results$AfterMatching[[x]]$ks$ks.boot.pvalue,2),
               NA))
    }))
    z <- as.data.frame(z)
    ##return(z)
    
    z[,2:9] <- apply(z[,2:9], 2, function(x){as.numeric(x)})
    mat <- z[,2:9]
    
    ## Apply the correct column names
    names(mat)<- c("Mean Tr.",
                   "Mean Con.",
                   "BM t p-value",
                   "AM t p-value",
                   "BM t stat",
                   "AM t stat",
                   "BM KS p-value",
                   "AM KS p-value")
    ## Apply the correct row names
    dimnames(mat)[[1]] <- z[,1]
    mat
  }
  
  
  ## Take the function above and apply it to the data supplied in the command
  results <- balanceMat(mb.results, covariates)
  
  ## set values of different parameters
  # pchset is the shape of the symbols
  # pchcolset is the color of the symbols
  xlim = c(xlim1,1); pchset = c(21,24,21,24); pchcolset = c("black","black", "red", "red")
  
  ## set margins and letter size
  par(cex=parcex, mai = c(0.5, 0.35, 1.1, 0.35))
  
  ## set number of rows to plot
  ny = nrow(results)
  
  ## create the empty figure
  if(!is.null(title))  plot(x=NULL,axes=F, xlim=xlim, ylim=c(1,ny),xlab="",ylab="", main=title)
  if(is.null(title))   plot(x=NULL,axes=F, xlim=xlim, ylim=c(1,ny),xlab="",ylab="")
  
  ## add the 0, 0.05 and 0.1 vertical lines
  abline(v=c(0,0.05,0.1),lty=c(1,4,4), lwd=c(1,2,2))
  axis(side=1,at=c(0,0.05,0.1,1),tick=TRUE, las=2, cex.axis=0.7)
  
  ## add labels on top of the three areas of the graph
  if(means==TRUE) axis(side=3,at=at1,labels="Mean\nTreated",tick=FALSE, padj=0.5,cex.axis=textsize)
  if(means==TRUE) axis(side=3,at=at2,labels="Mean\nControl",tick=FALSE, padj=0.5,cex.axis=textsize)
  axis(side=3,at=0.5,labels="P-values",tick=FALSE, padj=0.5,cex.axis=textsize)
  
  ## Fill the figure with the information which is inside the 'results' matrix
  ## Add the p-values of the t-statistics as points
  for(i in 3:4) points(results[,i],ny:1, pch = pchset[i-3+1], col = pchcolset[i-3+1], bg = pchcolset[i-3+1])
  ## Add the p-values of the ks statistics as points
  for(i in 7:8) points(results[,i],ny:1, pch = pchset[i-5+1], col = pchcolset[i-5+1], bg = pchcolset[i-5+1])
  
  
  ## Second, add each variable name and the means for treated and control
  for(i in 1:ny) {
    text(at3,ny-i+1,dimnames(results)[[1]][i],adj = 0,cex=textsize) # variable name
    if(means==TRUE) text(at1,ny-i+1,results[i,1], cex=textsize) # treatment mean
    if(means==TRUE) text(at2,ny-i+1,results[i,2], cex=textsize) # control mean
  }
  
  ## Add dotted horizontal lines every two variables to make it prettier
  for(i in seq(2,by=2,length.out=floor((ny-1)/2))) abline(h = i+0.5, lty = 3)
  
  ## Add legend
  # to move the legend change the x and y location
  if(legend) legend(x=-1,y=.7,
                    c(colnames(results)[3:4],
                      colnames(results)[7:8]),
                    pch=pchset,
                    pt.bg =
                      pchcolset,
                    cex=0.8,
                    ncol=2,
                    xpd=NA
  )
  
  return(results)
}

output38 <-  plot.pval(mb.results = bout.gm, covariates = X)
summary(mout.gm)

md<-data.frame(est = c(mout.gm$est), min95 = c(mout.gm$est-1.96*mout.gm$se),max95 = c(mout.gm$est+1.96*mout.gm$se),id=2)
eb <- read.dta("match1n.dta")

both.dfs <- rbind(md, eb) 

##########
#Figure 5#
##########

ggplot(both.dfs, aes(x=est, y = id)) +
  geom_point(size = 4) +
  geom_errorbarh(aes(xmax = max95, xmin = min95), height=.15) +
  scale_y_continuous(name="",breaks = c(1,2),limits = c(0.5, 2.5), labels = c("Entropy\nBalancing", "Genetic\nMatching")) +
  scale_x_continuous(limits = c(-.8, .1))+
  geom_vline(xintercept = 0, 
             linetype = 2, color = "black")+ xlab("Average Treatment Effect on the Treated") + ylab("") +
  theme(axis.title.x = element_text(size = 10), axis.title.y = element_text(size = 8), 
        axis.text.x = element_text(size = 8),axis.text.y = element_text(size = 8), 
        plot.title = element_text(face="bold", size=10,hjust = 0.5,vjust = -1)) +
  ggtitle("Data pre-processing Results") 
ggsave("Figure5.pdf", width = 22, height = 18, units = "cm")  


###########
#Figure A1#
###########

pdf("FigureA1.pdf")
plot.pval(mb.results = bout.gm, covariates = X)
dev.off()


###########
#Figure A2#
###########

rm(list = ls())

dat <- read.table("genmatch2.csv",header=T)
# covars
covars <- c("age1","age2","age3","age4","age5","age6","unemployed","publicsector","privatesector","entrepreneur","farmer","otherocc","ed1","ed2","ed3","ed4","female","rural","syriza","anel","pasok","river","goldendawn","abstain","other","stayeuro","leaveeuro","prscore")
X <- as.matrix(dat[,covars])


dat    <- data.frame(dat[,(names(dat) %in% covars)==F],X)
covars <- names(dat)[-which((names(dat) %in% c("negotiationbelief","referendumno")))]
X     <- dat[,covars]
X     <- as.matrix(X)
colnames(X) <-gsub("age1","18-24",colnames(X))
colnames(X) <-gsub("age2","25-34",colnames(X))
colnames(X) <-gsub("age3","35-44",colnames(X))
colnames(X) <-gsub("age4","45-54",colnames(X))
colnames(X) <-gsub("age5","55-64",colnames(X))
colnames(X) <-gsub("age6","65+",colnames(X))
colnames(X) <-gsub("unemployed","Unemployed",colnames(X))
colnames(X) <-gsub("publicsector","Public Sector",colnames(X))
colnames(X) <-gsub("privatesector","Private Sector",colnames(X))
colnames(X) <-gsub("entrepreneur","Entrepreneur",colnames(X))
colnames(X) <-gsub("farmer","Farmer",colnames(X))
colnames(X) <-gsub("otherocc","Other Occup.",colnames(X))
colnames(X) <-gsub("ed1","Primary Ed.",colnames(X))
colnames(X) <-gsub("ed2","Secondary Ed.",colnames(X))
colnames(X) <-gsub("ed3","Post-Secondary Ed.",colnames(X))
colnames(X) <-gsub("ed4","College",colnames(X))
colnames(X) <-gsub("female","Female",colnames(X))
colnames(X) <-gsub("rural","Rural",colnames(X))
colnames(X) <-gsub("syriza","Syriza",colnames(X))
colnames(X) <-gsub("anel","Ind.Greeks",colnames(X))
colnames(X) <-gsub("pasok","PASOK",colnames(X))
colnames(X) <-gsub("river","River",colnames(X))
colnames(X) <-gsub("goldendawn","Golden Dawn",colnames(X))
colnames(X) <-gsub("abstain","Abstain",colnames(X))
colnames(X) <-gsub("other","Other",colnames(X))
colnames(X) <-gsub("stayeuro","Stay in Euro",colnames(X))
colnames(X) <-gsub("leaveeuro","Leave Euro",colnames(X))
colnames(X) <-gsub("prscore","Propensity Score",colnames(X))
dat <- data.frame(dat,X)
Y <- dat$referendumno
W <- dat$negotiationbelief



g.weights <- GenMatch(Tr=W, X=X, BalanceMatrix=X, pop.size = 5000, estimand="ATT", M=1,print.level=0)
mout.gm <-  Match(Y,W,X,BiasAdjust=F,Weight.matrix=g.weights,estimand="ATT",M=1)
summary(mout.gm)
bout.gm <- MatchBalance(W~X,match.out = mout.gm,print.level=0)
bal.gm <- baltest.collect(matchbal.out=bout.gm,var.names=colnames(X),after=TRUE)
round(bal.gm,3)


plot.pval <- function(mb.results, covariates, title=NULL, means=TRUE, legend=TRUE,
                      legendx=0.15,legendy=2.2, textsize=0.9, parcex=0.8, at1=-0.35,
                      at2=-0.15, at3=-0.9,xlim1=-0.85){
  
  
  ## Check to make sure "covariates" is either a character vector or a matrix
  if(!(is.character(covariates)) & !(is.matrix(covariates))){
    stop("Error: The covariates must be either a character vector or a matrix with variable names")
  }
  
  
  
  balanceMat <- function(mb.results, covariates){
    
    ## Calculate the number of covariates
    ## If "covariates" is a matrix, take the number of columns; otherwise, take the number of
    ## elements in the vector
    n <- ifelse(class(covariates)=="matrix", dim(covariates)[2], length(covariates))
    
    ## Check to make sure that n is the same as the # of balance statistics
    bsCount <- length(mb.results$BeforeMatching)
    if(n != bsCount){stop("Error: the number of covariates does not match the size of the MatchBalance Results.")}
    
    ## Determine how the covariate names are provided, and then grab them
    if(class(covariates)=="matrix") rnames <- dimnames(covariates)[[2]]
    if(class(covariates)=="character") rnames <- covariates
    
    ## Construct the matrix of statistics from the MatchBalance data and attach it to the covariate names
    z <- t(sapply(1:n, function(x){
      c(rnames[x],
        round(mb.results$AfterMatching[[x]]$mean.Tr,3),
        round(mb.results$AfterMatching[[x]]$mean.Co,3),
        round(mb.results$BeforeMatching[[x]]$tt$p.value,2),
        round(mb.results$AfterMatching[[x]]$tt$p.value,2),
        round(mb.results$BeforeMatching[[x]]$tt$statistic,2),
        round(mb.results$AfterMatching[[x]]$tt$statistic,2),
        ifelse(is.null(mb.results$BeforeMatching[[x]]$ks$ks.boot.pvalue) ==
                 0,round(mb.results$BeforeMatching[[x]]$ks$ks.boot.pvalue,2),
               NA),
        
        ifelse(is.null(mb.results$AfterMatching[[x]]$ks$ks.boot.pvalue) ==
                 0, round(mb.results$AfterMatching[[x]]$ks$ks.boot.pvalue,2),
               NA))
    }))
    z <- as.data.frame(z)
    ##return(z)
    
    z[,2:9] <- apply(z[,2:9], 2, function(x){as.numeric(x)})
    mat <- z[,2:9]
    
    ## Apply the correct column names
    names(mat)<- c("Mean Tr.",
                   "Mean Con.",
                   "BM t p-value",
                   "AM t p-value",
                   "BM t stat",
                   "AM t stat",
                   "BM KS p-value",
                   "AM KS p-value")
    ## Apply the correct row names
    dimnames(mat)[[1]] <- z[,1]
    mat
  }
  
  
  ## Take the function above and apply it to the data supplied in the command
  results <- balanceMat(mb.results, covariates)
  
  ## set values of different parameters
  # pchset is the shape of the symbols
  # pchcolset is the color of the symbols
  xlim = c(xlim1,1); pchset = c(21,24,21,24); pchcolset = c("black","black", "red", "red")
  
  ## set margins and letter size
  par(cex=parcex, mai = c(0.5, 0.35, 1.1, 0.35))
  
  ## set number of rows to plot
  ny = nrow(results)
  
  ## create the empty figure
  if(!is.null(title))  plot(x=NULL,axes=F, xlim=xlim, ylim=c(1,ny),xlab="",ylab="", main=title)
  if(is.null(title))   plot(x=NULL,axes=F, xlim=xlim, ylim=c(1,ny),xlab="",ylab="")
  
  ## add the 0, 0.05 and 0.1 vertical lines
  abline(v=c(0,0.05,0.1),lty=c(1,4,4), lwd=c(1,2,2))
  axis(side=1,at=c(0,0.05,0.1,1),tick=TRUE, las=2, cex.axis=0.7)
  
  ## add labels on top of the three areas of the graph
  if(means==TRUE) axis(side=3,at=at1,labels="Mean\nTreated",tick=FALSE, padj=0.5,cex.axis=textsize)
  if(means==TRUE) axis(side=3,at=at2,labels="Mean\nControl",tick=FALSE, padj=0.5,cex.axis=textsize)
  axis(side=3,at=0.5,labels="P-values",tick=FALSE, padj=0.5,cex.axis=textsize)
  
  ## Fill the figure with the information which is inside the 'results' matrix
  ## Add the p-values of the t-statistics as points
  for(i in 3:4) points(results[,i],ny:1, pch = pchset[i-3+1], col = pchcolset[i-3+1], bg = pchcolset[i-3+1])
  ## Add the p-values of the ks statistics as points
  for(i in 7:8) points(results[,i],ny:1, pch = pchset[i-5+1], col = pchcolset[i-5+1], bg = pchcolset[i-5+1])
  
  
  ## Second, add each variable name and the means for treated and control
  for(i in 1:ny) {
    text(at3,ny-i+1,dimnames(results)[[1]][i],adj = 0,cex=textsize) # variable name
    if(means==TRUE) text(at1,ny-i+1,results[i,1], cex=textsize) # treatment mean
    if(means==TRUE) text(at2,ny-i+1,results[i,2], cex=textsize) # control mean
  }
  
  ## Add dotted horizontal lines every two variables to make it prettier
  for(i in seq(2,by=2,length.out=floor((ny-1)/2))) abline(h = i+0.5, lty = 3)
  
  ## Add legend
  # to move the legend change the x and y location
  if(legend) legend(x=-1,y=.7,
                    c(colnames(results)[3:4],
                      colnames(results)[7:8]),
                    pch=pchset,
                    pt.bg =
                      pchcolset,
                    cex=0.8,
                    ncol=2,
                    xpd=NA
  )
  
  return(results)
}

output39 <-  plot.pval(mb.results = bout.gm, covariates = X)
summary(mout.gm)

md<-data.frame(est = c(mout.gm$est), min95 = c(mout.gm$est-1.96*mout.gm$se),max95 = c(mout.gm$est+1.96*mout.gm$se),id=2)
eb <- read.dta("match2n.dta")

both.dfs <- rbind(md, eb) 



pdf("FigureA2.pdf")
plot.pval(mb.results = bout.gm, covariates = X)
dev.off()


###########
#Figure A5#
###########

ggplot(both.dfs, aes(x=est, y = id)) +
  geom_point(size = 4) +
  geom_errorbarh(aes(xmax = max95, xmin = min95), height=.15) +
  scale_y_continuous(name="",breaks = c(1,2),limits = c(0.5, 2.5), labels = c("Entropy\nBalancing", "Genetic\nMatching")) +
  scale_x_continuous(limits = c(-.1, .8))+
  geom_vline(xintercept = 0, 
             linetype = 2, color = "black")+ xlab("Average Treatment Effect on the Treated") + ylab("") +
  theme(axis.title.x = element_text(size = 10), axis.title.y = element_text(size = 8), 
        axis.text.x = element_text(size = 8),axis.text.y = element_text(size = 8), 
        plot.title = element_text(face="bold", size=10,hjust = 0.5,vjust = -1)) +
  ggtitle("Matching Results: Negoations-Belief") 
ggsave("FigureA5.pdf", width = 22, height = 18, units = "cm")  



###########
#Figure A6#
###########



rm(list=ls())


dat <- read.table("genmatch3.csv",header=T)


covars <- c("age1","age2","age3","age4","age5","age6","unemployed","publicsector","privatesector","entrepreneur","farmer","otherocc","ed1","ed2","ed3","ed4","female","rural","syriza","anel","pasok","river","goldendawn","abstain","other","stayeuro","leaveeuro","prscore2")
X <- as.matrix(dat[,covars])




dat    <- data.frame(dat[,(names(dat) %in% covars)==F],X)
covars <- names(dat)[-which((names(dat) %in% c("bankholidaychange","grexitbelief")))]
X     <- dat[,covars]
X     <- as.matrix(X)
colnames(X) <-gsub("age1","18-24",colnames(X))
colnames(X) <-gsub("age2","25-34",colnames(X))
colnames(X) <-gsub("age3","35-44",colnames(X))
colnames(X) <-gsub("age4","45-54",colnames(X))
colnames(X) <-gsub("age5","55-64",colnames(X))
colnames(X) <-gsub("age6","65+",colnames(X))
colnames(X) <-gsub("unemployed","Unemployed",colnames(X))
colnames(X) <-gsub("publicsector","Public Sector",colnames(X))
colnames(X) <-gsub("privatesector","Private Sector",colnames(X))
colnames(X) <-gsub("entrepreneur","Entrepreneur",colnames(X))
colnames(X) <-gsub("farmer","Farmer",colnames(X))
colnames(X) <-gsub("otherocc","Other Occup.",colnames(X))
colnames(X) <-gsub("ed1","Primary Ed.",colnames(X))
colnames(X) <-gsub("ed2","Secondary Ed.",colnames(X))
colnames(X) <-gsub("ed3","Post-Secondary Ed.",colnames(X))
colnames(X) <-gsub("ed4","College",colnames(X))
colnames(X) <-gsub("female","Female",colnames(X))
colnames(X) <-gsub("rural","Rural",colnames(X))
colnames(X) <-gsub("syriza","Syriza",colnames(X))
colnames(X) <-gsub("anel","Ind.Greeks",colnames(X))
colnames(X) <-gsub("pasok","PASOK",colnames(X))
colnames(X) <-gsub("river","River",colnames(X))
colnames(X) <-gsub("goldendawn","Golden Dawn",colnames(X))
colnames(X) <-gsub("abstain","Abstain",colnames(X))
colnames(X) <-gsub("other","Other",colnames(X))
colnames(X) <-gsub("stayeuro","Stay in Euro",colnames(X))
colnames(X) <-gsub("leaveeuro","Leave Euro",colnames(X))
colnames(X) <-gsub("prscore","Propensity Score",colnames(X))
dat <- data.frame(dat,X)
Y <- dat$grexitbelief
W <- dat$bankholidaychange




# Genetic Matching ATT
g.weights <- GenMatch(Tr=W, X=X, BalanceMatrix=X, pop.size = 5000, estimand="ATT", M=1,print.level=0)
mout.gm1 <-  Match(Y,W,X,BiasAdjust=F,Weight.matrix=g.weights,estimand="ATT",M=1)
summary(mout.gm1)
bout.gm <- MatchBalance(W~X,match.out = mout.gm1,print.level=0)
bal.gm <- baltest.collect(matchbal.out=bout.gm,var.names=colnames(X),after=TRUE)
round(bal.gm,3)



plot.pval <- function(mb.results, covariates, title=NULL, means=TRUE, legend=TRUE,
                      legendx=0.15,legendy=2.2, textsize=0.9, parcex=0.8, at1=-0.35,
                      at2=-0.15, at3=-0.9,xlim1=-0.85){
  
  
  ## Check to make sure "covariates" is either a character vector or a matrix
  if(!(is.character(covariates)) & !(is.matrix(covariates))){
    stop("Error: The covariates must be either a character vector or a matrix with variable names")
  }
  
  
  
  balanceMat <- function(mb.results, covariates){
    
    ## Calculate the number of covariates
    ## If "covariates" is a matrix, take the number of columns; otherwise, take the number of
    ## elements in the vector
    n <- ifelse(class(covariates)=="matrix", dim(covariates)[2], length(covariates))
    
    ## Check to make sure that n is the same as the # of balance statistics
    bsCount <- length(mb.results$BeforeMatching)
    if(n != bsCount){stop("Error: the number of covariates does not match the size of the MatchBalance Results.")}
    
    ## Determine how the covariate names are provided, and then grab them
    if(class(covariates)=="matrix") rnames <- dimnames(covariates)[[2]]
    if(class(covariates)=="character") rnames <- covariates
    
    ## Construct the matrix of statistics from the MatchBalance data and attach it to the covariate names
    z <- t(sapply(1:n, function(x){
      c(rnames[x],
        round(mb.results$AfterMatching[[x]]$mean.Tr,3),
        round(mb.results$AfterMatching[[x]]$mean.Co,3),
        round(mb.results$BeforeMatching[[x]]$tt$p.value,2),
        round(mb.results$AfterMatching[[x]]$tt$p.value,2),
        round(mb.results$BeforeMatching[[x]]$tt$statistic,2),
        round(mb.results$AfterMatching[[x]]$tt$statistic,2),
        ifelse(is.null(mb.results$BeforeMatching[[x]]$ks$ks.boot.pvalue) ==
                 0,round(mb.results$BeforeMatching[[x]]$ks$ks.boot.pvalue,2),
               NA),
        
        ifelse(is.null(mb.results$AfterMatching[[x]]$ks$ks.boot.pvalue) ==
                 0, round(mb.results$AfterMatching[[x]]$ks$ks.boot.pvalue,2),
               NA))
    }))
    z <- as.data.frame(z)
    ##return(z)
    
    z[,2:9] <- apply(z[,2:9], 2, function(x){as.numeric(x)})
    mat <- z[,2:9]
    
    ## Apply the correct column names
    names(mat)<- c("Mean Tr.",
                   "Mean Con.",
                   "BM t p-value",
                   "AM t p-value",
                   "BM t stat",
                   "AM t stat",
                   "BM KS p-value",
                   "AM KS p-value")
    ## Apply the correct row names
    dimnames(mat)[[1]] <- z[,1]
    mat
  }
  
  
  ## Take the function above and apply it to the data supplied in the command
  results <- balanceMat(mb.results, covariates)
  
  ## set values of different parameters
  # pchset is the shape of the symbols
  # pchcolset is the color of the symbols
  xlim = c(xlim1,1); pchset = c(21,24,21,24); pchcolset = c("black","black", "red", "red")
  
  ## set margins and letter size
  par(cex=parcex, mai = c(0.5, 0.35, 1.1, 0.35))
  
  ## set number of rows to plot
  ny = nrow(results)
  
  ## create the empty figure
  if(!is.null(title))  plot(x=NULL,axes=F, xlim=xlim, ylim=c(1,ny),xlab="",ylab="", main=title)
  if(is.null(title))   plot(x=NULL,axes=F, xlim=xlim, ylim=c(1,ny),xlab="",ylab="")
  
  ## add the 0, 0.05 and 0.1 vertical lines
  abline(v=c(0,0.05,0.1),lty=c(1,4,4), lwd=c(1,2,2))
  axis(side=1,at=c(0,0.05,0.1,1),tick=TRUE, las=2, cex.axis=0.7)
  
  ## add labels on top of the three areas of the graph
  if(means==TRUE) axis(side=3,at=at1,labels="Mean\nTreated",tick=FALSE, padj=0.5,cex.axis=textsize)
  if(means==TRUE) axis(side=3,at=at2,labels="Mean\nControl",tick=FALSE, padj=0.5,cex.axis=textsize)
  axis(side=3,at=0.5,labels="P-values",tick=FALSE, padj=0.5,cex.axis=textsize)
  
  ## Fill the figure with the information which is inside the 'results' matrix
  ## Add the p-values of the t-statistics as points
  for(i in 3:4) points(results[,i],ny:1, pch = pchset[i-3+1], col = pchcolset[i-3+1], bg = pchcolset[i-3+1])
  ## Add the p-values of the ks statistics as points
  for(i in 7:8) points(results[,i],ny:1, pch = pchset[i-5+1], col = pchcolset[i-5+1], bg = pchcolset[i-5+1])
  
  
  ## Second, add each variable name and the means for treated and control
  for(i in 1:ny) {
    text(at3,ny-i+1,dimnames(results)[[1]][i],adj = 0,cex=textsize) # variable name
    if(means==TRUE) text(at1,ny-i+1,results[i,1], cex=textsize) # treatment mean
    if(means==TRUE) text(at2,ny-i+1,results[i,2], cex=textsize) # control mean
  }
  
  ## Add dotted horizontal lines every two variables to make it prettier
  for(i in seq(2,by=2,length.out=floor((ny-1)/2))) abline(h = i+0.5, lty = 3)
  
  ## Add legend
  # to move the legend change the x and y location
  if(legend) legend(x=-1,y=.7,
                    c(colnames(results)[3:4],
                      colnames(results)[7:8]),
                    pch=pchset,
                    pt.bg =
                      pchcolset,
                    cex=0.8,
                    ncol=2,
                    xpd=NA
  )
  
  return(results)
}

output39 <-  plot.pval(mb.results = bout.gm, covariates = X)







pdf("FigureA6.pdf")
plot.pval(mb.results = bout.gm, covariates = X)
dev.off()



############
#Figure  A7#
############




dat <- read.table("genmatch4.csv",header=T)


covars <- c("age1","age2","age3","age4","age5","age6","unemployed","publicsector","privatesector","entrepreneur","farmer","otherocc","ed1","ed2","ed3","ed4","female","rural","syriza","anel","pasok","river","goldendawn","abstain","other","stayeuro","leaveeuro","prscore3")
X <- as.matrix(dat[,covars])




dat    <- data.frame(dat[,(names(dat) %in% covars)==F],X)
covars <- names(dat)[-which((names(dat) %in% c("bankholidaychange","negotiationbelief")))]
X     <- dat[,covars]
X     <- as.matrix(X)
colnames(X) <-gsub("age1","18-24",colnames(X))
colnames(X) <-gsub("age2","25-34",colnames(X))
colnames(X) <-gsub("age3","35-44",colnames(X))
colnames(X) <-gsub("age4","45-54",colnames(X))
colnames(X) <-gsub("age5","55-64",colnames(X))
colnames(X) <-gsub("age6","65+",colnames(X))
colnames(X) <-gsub("unemployed","Unemployed",colnames(X))
colnames(X) <-gsub("publicsector","Public Sector",colnames(X))
colnames(X) <-gsub("privatesector","Private Sector",colnames(X))
colnames(X) <-gsub("entrepreneur","Entrepreneur",colnames(X))
colnames(X) <-gsub("farmer","Farmer",colnames(X))
colnames(X) <-gsub("otherocc","Other Occup.",colnames(X))
colnames(X) <-gsub("ed1","Primary Ed.",colnames(X))
colnames(X) <-gsub("ed2","Secondary Ed.",colnames(X))
colnames(X) <-gsub("ed3","Post-Secondary Ed.",colnames(X))
colnames(X) <-gsub("ed4","College",colnames(X))
colnames(X) <-gsub("female","Female",colnames(X))
colnames(X) <-gsub("rural","Rural",colnames(X))
colnames(X) <-gsub("syriza","Syriza",colnames(X))
colnames(X) <-gsub("anel","Ind.Greeks",colnames(X))
colnames(X) <-gsub("pasok","PASOK",colnames(X))
colnames(X) <-gsub("river","River",colnames(X))
colnames(X) <-gsub("goldendawn","Golden Dawn",colnames(X))
colnames(X) <-gsub("abstain","Abstain",colnames(X))
colnames(X) <-gsub("other","Other",colnames(X))
colnames(X) <-gsub("stayeuro","Stay in Euro",colnames(X))
colnames(X) <-gsub("leaveeuro","Leave Euro",colnames(X))
colnames(X) <-gsub("prscore","Propensity Score",colnames(X))
dat <- data.frame(dat,X)
Y <- dat$negotiationbelief
W <- dat$bankholidaychange




# Genetic Matching ATT
g.weights <- GenMatch(Tr=W, X=X, BalanceMatrix=X, pop.size = 5000, estimand="ATT", M=1,print.level=0)
mout.gm2 <-  Match(Y,W,X,BiasAdjust=F,Weight.matrix=g.weights,estimand="ATT",M=1)
summary(mout.gm2)
bout.gm <- MatchBalance(W~X,match.out = mout.gm2,print.level=0)
bal.gm <- baltest.collect(matchbal.out=bout.gm,var.names=colnames(X),after=TRUE)
round(bal.gm,3)


md1<-data.frame(est = c(mout.gm1$est), min95 = c(mout.gm1$est-1.96*mout.gm1$se),max95 = c(mout.gm1$est+1.96*mout.gm1$se),id1=2,id2=1)
eb1 <- read.dta("match3n.dta")

both.dfs1 <- rbind(md1, eb1) 

md2<-data.frame(est = c(mout.gm2$est), min95 = c(mout.gm2$est-1.96*mout.gm2$se),max95 = c(mout.gm2$est+1.96*mout.gm2$se),id1=2,id2=2)
eb2 <- read.dta("match4n.dta")

both.dfs2 <- rbind(md2, eb2)

both.dfs.all <- rbind(both.dfs1,both.dfs2)

both.dfs.all$id3<-as.factor(both.dfs.all$id1)

p1<-ggplot(both.dfs.all, aes(x=id2, y = est,color=id3)) + coord_flip() +  
  geom_point(size = 2,position=position_dodge(0.2)) +
  scale_color_manual(name="",labels=c("Entropy\nBalancing", "Genetic\nMatching"),values=c("red","blue")) + 
  geom_errorbar(aes(ymax = max95, ymin = min95),width=.2, position=position_dodge(width=0.2)) +
  scale_x_continuous(name="",limits = c(0.7, 2.3), breaks = c(1,2), labels = c("Grexit","Negotiations")) +
  scale_y_continuous(limits = c(-.3, .5), "Treatment Effect")+ ggtitle("Impact of Bank Closure\n on Expectations") +
  geom_hline(yintercept = 0, 
             linetype = 2, color = "black") + guides(fill=guide_legend(reverse=TRUE), 
                                                     colour=guide_legend(reverse=TRUE)) +
  theme(axis.title.x = element_text(size = 8), axis.title.y = element_text(size = 8), 
        axis.text.x = element_text(size = 8),axis.text.y = element_text(size = 8), 
        plot.title = element_text(face="bold", size=10,hjust = 0.5,vjust = -1))  
ggsave("Figure7.pdf", width = 22, height = 18, units = "cm")
p1


